/**
 * @author Javen 
 * @copyright 2018-10-30 15:53:56 javendev@126.com 
 * @description 粒子资源测试
 */


/**
 * 使用resetSystem来控制
 */
cc.Class({
    extends: cc.Component,

    properties: {
        click: {
            default: null,
            type: cc.Prefab,
        }
    },

    newClickNode(position) {
        let newNode = null;
        if (!this._clickPool) {
            this._clickPool = new cc.NodePool();
        }
        if (this._clickPool.size() > 0) {
            newNode = this._clickPool.get();
        } else {
            newNode = cc.instantiate(this.click);
        }
        newNode.name = "clickNode";
        newNode.setPosition(position);
        this.node.addChild(newNode);
        return newNode;
    },


    // onLoad () {},

    start() {
        this._initNodeTouchEvent();
    },
    _initNodeTouchEvent() {
        //监听事件
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegin, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
    },

    _destroyTouchEvent() {
        //销毁事件
        this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegin, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
        cc.log("销毁事件...");
    },

    _onTouchBegin: function (event) {
        //获取当前点击的全局坐标
        let temp = event.getLocation();
        //获取当前点击的局部坐标
        let tempClick = this.node.convertToNodeSpaceAR(temp)
        let newNode = this.newClickNode(tempClick);

        newNode.getComponent(cc.ParticleSystem).resetSystem();

        cc.log("子节点数:" + this.node.children.length);

        this.node.children.forEach(element => {

            if (element.name === 'clickNode') {
                let particle = element.getComponent(cc.ParticleSystem);
                if (particle.stopped) {
                    this._clickPool.put(element);
                    cc.log("顺利回收...");
                }
            }

        });
    },

    _onTouchMoved: function (event) {
        cc.log('_onTouchMoved');
    },

    _onTouchEnd: function (event) {
        cc.log('_onTouchEnd');
    },

    _onTouchCancel: function (event) {
        cc.log('_onTouchCancel');
    },

    onDestroy() {
        //销毁事件
        this._destroyTouchEvent();
    },
    toBack() {
        cc.director.loadScene("Scene");
    },

    // update (dt) {},
});